﻿using System.Text;

namespace Water
{
    public static class IniFileHelper
    {
        public const string WaterSet = nameof(WaterSet);
        private static string IniFilePath => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "water", "config.ini");
        private static string DirIniFilePath => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "water");


        public static string ReadValue(string key)
        {
            string value = string.Empty;
            if (File.Exists(IniFilePath))
            {
                var lines = File.ReadAllLines(IniFilePath, Encoding.Default);
                var line = lines.FirstOrDefault(x => x.Contains(key + "="));
                if (line != null)
                {
                    return line.Split("=")[1];
                }
            }
            return value;
        }

        public static void WriteValue(string key, string value)
        {
            var lines = new List<string>();

            if (File.Exists(IniFilePath))
            {
                lines = File.ReadAllLines(IniFilePath, Encoding.Default).ToList();
            }
            else
            {
                Directory.CreateDirectory(DirIniFilePath);
                File.Create(IniFilePath).Close();
            }

            var line = lines.FirstOrDefault(x => x.Contains(key + "="));
            if (line != null)
            {
                lines.Remove(line);
            }
            lines.Insert(lines.Count, $"{key}={value}");

            File.WriteAllLines(IniFilePath, lines, Encoding.Default);
        }
        public static void IniFile()
        {
            if (!File.Exists(IniFilePath))
            {
                WriteValue(WaterSet, "0");
            }

        }
    }
}
